package pnu.ssm.adapter;

import java.util.ArrayList;

import pnu.ssm.appinfo.AppInfo;
import pnu.ssm.sbmother.R;
import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.TextView;
import android.widget.ToggleButton;

public class AppInfoListAdapter extends BaseAdapter{
	
	public static final String TAG = "AppInfoListAdapter";
	Context context;
	LayoutInflater Inflater;
	ArrayList<AppInfo> listAppInfo;
	int layout;
	
	public AppInfoListAdapter(Context context, int layout, ArrayList<AppInfo> listAppInfo){
		this.context = context;
		this.Inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		this.listAppInfo = listAppInfo;
		this.layout = layout;
	}
	
	public void setList(ArrayList<AppInfo> list) {
		this.listAppInfo = list;
	}
	
	@Override
	public int getCount() {
		return listAppInfo.size();
	}

	@Override
	public String getItem(int position) {
		return listAppInfo.get(position).getAppName();
	}

	@Override
	public long getItemId(int position) {
		return position;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		if(convertView == null){
			convertView = Inflater.inflate(layout, parent, false);
		}
		final int pos = position;
		final TextView btnAndroidAppName = (TextView)convertView.findViewById(R.id.tv_android_app_name);
		final TextView btnAndroidPackageName = (TextView)convertView.findViewById(R.id.tv_android_package_name);
		final ToggleButton btnToggleAppState = (ToggleButton) convertView.findViewById(R.id.btn_toggle_android_app_state);
		final AppInfo info = listAppInfo.get(pos);
		
		btnAndroidAppName.setText(info.getAppName());
		btnAndroidPackageName.setText(info.getPackageName());
		btnToggleAppState.setChecked(info.isCheck());
		
		btnToggleAppState.setOnClickListener(new Button.OnClickListener(){
			@Override
			public void onClick(View v) {
				if(btnToggleAppState.isChecked() == true){
					info.setCheck(true);
				}else{
					info.setCheck(false);
				}
				info.setChanged(true); // 상태를 한번이라도 바꾸면 changed.
				Log.d(TAG, "check : "+btnToggleAppState.isChecked()+", changed : "+info.isChanged());
			}
		});
		return convertView;
	}
}
